<template>
  <div class="message-notification">
    <el-popover
      placement="bottom"
      width="350"
      trigger="click"
      @show="loadMessages">
      <div class="message-header">
        <span>消息通知</span>
        <el-button type="text" @click="markAllRead" v-if="messages.length > 0">全部已读</el-button>
      </div>
      
      <div class="message-list" v-if="messages.length > 0">
        <div v-for="(msg, index) in messages" :key="msg.id" 
             class="message-item" 
             :class="{ 'unread': msg.readStatus === 0 }"
             @click="readMessage(msg)">
          <div class="message-title">{{ msg.title }}</div>
          <div class="message-content">{{ msg.content }}</div>
          <div class="message-time">{{ formatTime(msg.createTime) }}</div>
        </div>
      </div>
      
      <div v-else class="no-message">
        暂无消息
      </div>
      
      <el-button slot="reference" type="text">
        <el-badge :value="unreadCount > 0 ? unreadCount : ''" class="message-badge">
          <i class="el-icon-bell"></i>
        </el-badge>
      </el-button>
    </el-popover>
    
    <!-- 新消息弹窗 -->
    <el-dialog
      title="新消息"
      :visible.sync="newMessageVisible"
      width="400px"
      :show-close="true"
      center>
      <div class="new-message-content">
        <h3>{{ newMessage.title }}</h3>
        <p>{{ newMessage.content }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newMessageVisible = false">关闭</el-button>
        <el-button type="primary" @click="viewMessageDetail">查看详情</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { formatDate } from '@/utils/date'

export default {
  name: 'MessageNotification',
  data() {
    return {
      messages: [],
      unreadCount: 0,
      timer: null,
      lastCheckTime: Date.now(),
      newMessageVisible: false,
      newMessage: {
        id: null,
        title: '',
        content: ''
      }
    }
  },
  created() {
    this.fetchUnreadCount()
    // 定时获取未读消息数量和检查新消息
    this.timer = setInterval(this.checkNewMessages, 10000) // 每10秒检查一次
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    formatTime(time) {
      return formatDate(time)
    },
    async fetchUnreadCount() {
      try {
        // 从user对象中获取userId
        const userStr = localStorage.getItem('user');
        let userId = null;
        
        if (userStr) {
          try {
            const user = JSON.parse(userStr);
            userId = user.id;
          } catch (e) {
            console.error('解析用户信息失败', e);
          }
        }
        
        console.log('当前用户ID:', userId);
        
        if (!userId) {
          console.log('用户ID未找到，无法获取消息');
          return;
        }
        
        const res = await axios.get(`/api/message/unread?userId=${userId}`).then(res => res.data);
        console.log('未读消息响应:', res);
        
        if (res.code === 200) {
          this.unreadCount = res.data;
        }
      } catch (error) {
        console.error('获取未读消息数量失败', error);
      }
    },
    async loadMessages() {
      try {
        // 从user对象中获取userId
        const userStr = localStorage.getItem('user');
        let userId = null;
        
        if (userStr) {
          try {
            const user = JSON.parse(userStr);
            userId = user.id;
          } catch (e) {
            console.error('解析用户信息失败', e);
          }
        }
        
        console.log('加载消息的用户ID:', userId);
        
        if (!userId) return;
        
        const res = await axios.get(`/api/message/list?userId=${userId}`).then(res => res.data);
        console.log('消息列表响应:', res);
        
        if (res.code === 200) {
          this.messages = res.data;
          console.log('获取到的消息数量:', this.messages.length);
        }
      } catch (error) {
        console.error('获取消息列表失败', error);
      }
    },
    async readMessage(msg) {
      if (msg.readStatus === 0) {
        try {
          await axios.put(`/api/message/read/${msg.id}`).then(res => res.data)
          // 更新消息状态
          msg.readStatus = 1
          // 更新未读数量
          this.fetchUnreadCount()
        } catch (error) {
          console.error('标记消息已读失败', error)
        }
      }
      
      // 可以实现点击消息后的导航逻辑
    },
    async markAllRead() {
      const unreadMessages = this.messages.filter(msg => msg.readStatus === 0)
      if (unreadMessages.length === 0) return
      
      try {
        for (const msg of unreadMessages) {
          await axios.put(`/api/message/read/${msg.id}`).then(res => res.data)
          msg.readStatus = 1
        }
        this.unreadCount = 0
      } catch (error) {
        console.error('标记全部已读失败', error)
      }
    },
    async checkNewMessages() {
      await this.fetchUnreadCount()
      
      // 如果有未读消息，获取最新的一条
      if (this.unreadCount > 0) {
        try {
          const userId = localStorage.getItem('userId')
          if (!userId) return
          
          const res = await axios.get(`/api/message/list?userId=${userId}`).then(res => res.data)
          if (res.code === 200 && res.data.length > 0) {
            // 获取未读消息
            const unreadMessages = res.data.filter(msg => msg.readStatus === 0)
            if (unreadMessages.length > 0) {
              // 获取最新的一条未读消息
              const latestMessage = unreadMessages[0]
              
              // 检查是否是订单完成通知
              if (latestMessage.title.includes('订单已完成') && 
                  Date.now() - new Date(latestMessage.createTime).getTime() < 60000) { // 1分钟内的消息
                this.newMessage = latestMessage
                this.newMessageVisible = true
              }
            }
          }
        } catch (error) {
          console.error('检查新消息失败', error)
        }
      }
    },
    viewMessageDetail() {
      // 标记消息为已读
      this.readMessage(this.newMessage)
      // 关闭弹窗
      this.newMessageVisible = false
      // 可以添加导航到订单详情页的逻辑
      // this.$router.push(`/order/${this.newMessage.orderNo}`)
    }
  }
}
</script>

<style scoped>
.message-notification {
  display: inline-block;
}
.message-badge {
  font-size: 20px;
}
.message-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}
.message-list {
  max-height: 300px;
  overflow-y: auto;
}
.message-item {
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}
.message-item:hover {
  background-color: #f5f7fa;
}
.message-item.unread {
  background-color: #ecf5ff;
}
.message-title {
  font-weight: bold;
  margin-bottom: 5px;
}
.message-content {
  color: #666;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.message-time {
  color: #999;
  font-size: 12px;
  text-align: right;
}
.no-message {
  text-align: center;
  color: #999;
  padding: 20px 0;
}
.new-message-content {
  text-align: center;
}
</style> 